import showModal from '@/utils/showModalHandler'
import token from '@/request/token/token'
import CryptoJS from '@/utils/crypto'
import cacheHandler from '@/utils/cacheHandler'
import xml2js from '@/utils/xml2js'
import { config } from '@/config/systemConfig'

/**
 * 图片上传
 */
function uploadFile(fileName, file, formData) {
  uni.showLoading({
    title: '正在加载'
  })
  return new Promise(function(resolve, reject) {
    token.get().then(tokenValue => {
      formData.token = tokenValue.token
      formData.app_id = cacheHandler.getDhccAppId()
      authorizeParams(formData.biz_content, tokenValue.authToken).then(res => {
        console.log(formData.method + '--request params:', res)
        formData.biz_content = res
        formData.sign = CryptoJS.encryptSign(formData)
        formData.biz_content = CryptoJS.encrypt(formData.biz_content)
        let url = config.DHCCAM_URL
        // #ifdef H5
        url = config.BASE_URL + url
        // #endif
        url = url + '?method=' + formData.method
        uni.uploadFile({
          url: url,
          filePath: file,
          name: fileName,
          formData: formData,
          // header: {
          //   'Content-Type': 'multipart/form-data'
          // },
          success: function(res) {
            uni.hideLoading()
            if (res.statusCode === 200) {
              let data = JSON.parse(res.data)
              if (data.code === '10000') {
                var dataJson = CryptoJS.decrypt(data.data)
                console.log(formData.method + '--decrypt responseData:', dataJson)
                resolve(JSON.parse(dataJson))
              } else {
                showModal.showToast(data.msg)
                reject(data.msg)
              }
            } else {
              showModal.showToast('网络请求失败，请稍后重试！')
              reject(res.errMsg)
            }
          },
          fail: function(err) {
            uni.hideLoading()
            reject(err)
          }
        })
      })
    })
  })
}

/**
 * ocr图片上传
 */
function ocrUploadFile(fileName, file, formData) {
  uni.showLoading({
    title: '正在加载'
  })
  return new Promise(function(resolve, reject) {
    formData.token = config.OCR_GATEWAY_TOKEN
    uni.uploadFile({
      url: config.OCR_GATEWAY_URL,
      filePath: file,
      name: fileName,
      formData: formData,
      // header: {
      //   'Content-Type': 'multipart/form-data'
      // },
      success: function(res) {
        uni.hideLoading()
        if (res.statusCode === 200) {
          let data = JSON.parse(res.data)
          if (data.code === '10000') {
            resolve(JSON.parse(data.data))
          } else {
            showModal.showToast(data.msg)
            reject(data.msg)
          }
        } else {
          showModal.showToast('网络请求失败，请稍后重试！')
          reject(res.errMsg)
        }
      },
      fail: function(err) {
        uni.hideLoading()
        reject(err)
      }
    })
  })
}

/**
 * 组装ocr的form-data请求数据
 */
function ocrUploadFileFormData(method, version, bizContent, appId = config.OCR_GATEWAY_APPID) {
  return getRequestObject(method, version, bizContent, appId)
}

/**
 * 组装form-data请求数据
 */
function uploadFileFormData(method, version, bizContent) {
  return getRequestObject(method, version, bizContent)
}

/**
 * 组装application/json请求数据
 */
function generateRequest(method, version, bizContent) {
  return getRequestObject(method, version, bizContent)
}

/**
 * 请求对象, 请求格式为json和form-data时共用
 */
function getRequestObject(method, version, bizContent, appId = '') {
  return {
    method: method,
    app_id: appId,
    token_type: 'api_credentials',
    nonce_str: new Date().getTime(),
    version: version,
    token: '',
    biz_content: bizContent
  }
}

/**
 * his请求内容需要组织一下
 * @param {STRING} bizContent
 */
function hisBizContent(bizContent) {
  return {
    requestXML: bizContent
  }
}

function gatewayRequest(data = {}, method = 'POST', url = config.DHCCAM_URL) {
  uni.showLoading({
    title: '正在加载'
  })
  return new Promise((resolve, reject) => {
    token.get().then(tokenValue => {
      /* data.token = tokenValue.token
      data.app_id = cacheHandler.getDhccAppId()
      authorizeParams(data.biz_content, tokenValue.authToken).then(res => {
			  console.log(data.method + '--request params:', res)
        data.biz_content = res
        data.sign = CryptoJS.encryptSign(data)
        data.biz_content = CryptoJS.encrypt(data.biz_content)
        request(data, method, url).then(res => {
          res = CryptoJS.decrypt(res)
          console.log(data.method + '--decrypt responseData:', res)
          uni.hideLoading()
          resolve(res)
        }).catch(err => {
          uni.hideLoading()
          reject(err)
        })
      }) */
	  request(data, method, url).then(res => {
	    //res = CryptoJS.decrypt(res)
	    console.log(data.method + '--decrypt responseData:', res)
	    uni.hideLoading()
	    resolve(res)
	  }).catch(err => {
	    uni.hideLoading()
	    reject(err)
	  })
    })
  })
}

function gatewayRequestNoLoading(data = {}, method = 'POST', url = config.DHCCAM_URL) {
  return new Promise((resolve, reject) => {
    token.get().then(tokenValue => {
      data.token = tokenValue.token
      data.app_id = cacheHandler.getDhccAppId()
      authorizeParams(data.biz_content, tokenValue.authToken).then(res => {
        console.log(data.method + '--request params:', res)
        data.biz_content = res
        data.sign = CryptoJS.encryptSign(data)
        data.biz_content = CryptoJS.encrypt(data.biz_content)
        request(data, method, url).then(res => {
          res = CryptoJS.decrypt(res)
          console.log(data.method + '--decrypt responseData:', res)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    })
  })
}

/**
 * bizcontent加入authToken
 */
function authorizeParams(content, authToken) {
  return new Promise((resolve, reject) => {
    try {
      if (content.body) {
        content.body.authToken = authToken
        resolve(content)
      }
      if (content.query) {
        content.query.authToken = authToken
        resolve(content)
      }
      if (content.requestXML) {
        xml2js.xml2json(content.requestXML).then(res => {
          res.Request.authToken = authToken
          content.requestXML = xml2js.json2xml(res.Request)
          resolve(content)
        })
      }
      if (!content.body && !content.query && !content.requestXML) {
        resolve(content)
      }
    } catch (e) {
      reject(e)
    }
  })
}

function request(data = {}, method = 'POST', url = config.DHCCAM_URL) {
  return new Promise(function(resolve, reject) {
    // 解决h5开发环境跨域问题
    // #ifdef H5
    url = config.BASE_URL + url
    // #endif
    url = url + '?method=' + data.method
    uni.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        if (res.statusCode === 200) {
          if (res.data.code === '10000') {
            resolve(res.data.data)
          } else {
            if (res.data.code === 50001) {
              token.remove()
            }
            showModal.showToast(res.data.msg)
            reject(res.data.msg)
          }
        } else {
          showModal.showToast('网络请求失败，请稍后重试！')
          reject(res.errMsg)
        }
      },
      fail: function(err) {
        console.log('response err', err)
        reject(err)
      },
      complete: function() {
        uni.hideLoading()
      }
    })
  })
}

/**
 * 支付宝微信小程序和微站走这个请求
 */
function loginRequest(data = {}, url = config.LOGIN_URL, method = 'POST') {
  return new Promise(function(resolve, reject) {
    // 解决h5开发环境跨域问题
    // #ifdef H5
    url = config.BASE_URL + url
    // #endif
    uni.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log('loginRequest res', res)
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          showModal.showToast('网络请求失败，请稍后重试！')
          reject(res.errMsg)
        }
      },
      fail: function(err) {
        console.log('loginRequest err', err)
        reject(err)
      },
      complete: function() {
        uni.hideLoading()
      }
    })
  })
}

/**
 * php框架对服务号和生活号有传参要求，所以单独提出一个请求方法
 */
function loginH5Request(data = {}, method = 'POST') {
  return new Promise(function(resolve, reject) {
    let code = data.code
    let url = data.url
    url = config.BASE_URL + url
    url = `${url}?code=${code}`
    console.log('loginH5Request url', url)
    uni.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        console.log('loginH5Request res', res)
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          showModal.showToast('网络请求失败，请稍后重试！')
          reject(res.errMsg)
        }
      },
      fail: function(err) {
        console.log('loginH5Request err', err)
        reject(err)
      },
      complete: function() {
        uni.hideLoading()
      }
    })
  })
}

/**
 * 互联网后台接口返回统一处理
 */
function handleSpIhospitalResponse(response) {
  response = JSON.parse(response)
  if (response && response.code === 20000) {
    return response.data ? response.data : ''
  }
  return Promise.reject(response.message)
}

export default {
  uploadFile,
  ocrUploadFile,
  ocrUploadFileFormData,
  uploadFileFormData,
  generateRequest,
  hisBizContent,
  gatewayRequest,
  gatewayRequestNoLoading,
  request,
  loginRequest,
  loginH5Request,
  handleSpIhospitalResponse
}
